import { useState, useEffect } from 'react';
import { Bar, Line, Pie } from 'react-chartjs-2';
import {
    BarElement,
    LineElement,
    PointElement,
    ArcElement,
    CategoryScale,
    Chart as ChartJS,
    Legend,
    LinearScale,
    Title,
    Tooltip
} from "chart.js";
import axios from 'axios'; // 用于请求后端数据

// 注册 Chart.js 模块
ChartJS.register(
    BarElement,
    LineElement,
    PointElement,
    ArcElement,
    CategoryScale,
    LinearScale,
    Title,
    Tooltip,
    Legend
);

function ChartPage() {
    const [chartType, setChartType] = useState('bar'); // 默认显示柱状图
    const [chartData, setChartData] = useState(null); // 存储从后端获取的数据
    const [error, setError] = useState(null); // 错误信息

    const userId = 1; // 模拟用户 ID

    // 从后端获取数据
    useEffect(() => {
        const fetchData = async () => {
            try {
                setError(null); // 清除之前的错误
                const response = await axios.get(`http://localhost:8080/api/LEARNING_STATS/${userId}`); // 后端 API 地址
                const learningData = response.data; // 后端返回的数据

                // 格式化数据以适配 Chart.js
                const labels = learningData.map(item => item.studyType); // 提取学习类型
                const data = learningData.map(item => item.hoursSpent); // 提取学习时长

                // 设置图表数据
                setChartData({
                    labels: labels,
                    datasets: [
                        {
                            label: 'Hours_Spent (学习时间)',
                            data: data,
                            backgroundColor: [
                                'rgba(75, 192, 192, 0.6)',
                                'rgba(153, 102, 255, 0.6)',
                                'rgba(255, 159, 64, 0.6)',
                                'rgba(54, 162, 235, 0.6)',
                                'rgba(255, 99, 132, 0.6)',
                            ],
                            borderColor: [
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                                'rgba(255, 159, 64, 1)',
                                'rgba(54, 162, 235, 1)',
                                'rgba(255, 99, 132, 1)',
                            ],
                            borderWidth: 1,
                        },
                    ],
                });
            } catch (error) {
                setError('Failed to fetch data. Please try again later.'); // 设置错误信息
                console.error('Error fetching data:', error);
            }
        };

        fetchData();
    }, [userId]);

    // 图表选项配置
    const options = {
        responsive: true,
        plugins: {
            legend: {
                position: 'top',
            },
            title: {
                display: true,
                text: 'English Learning Time Distribution (英语学习时间分布)',
            },
        },
    };

    // 更改图表类型的处理函数
    const handleChartTypeChange = (event) => {
        setChartType(event.target.value); // 更新图表类型
    };

    // 根据当前选择的图表类型动态渲染图表组件
    const renderChart = () => {
        if (!chartData) {
            return <p>Loading chart data...</p>; // 数据加载中
        }

        switch (chartType) {
            case 'bar':
                return <Bar data={chartData} options={options} />;
            case 'line':
                return <Line data={chartData} options={options} />;
            case 'pie':
                return <Pie data={chartData} options={options} />;
            default:
                return null;
        }
    };

    return (
        <div className="chart-container">
            <h3>Select a Chart Type (选择图表类型)</h3>
            <select onChange={handleChartTypeChange} value={chartType} className="chart-select">
                <option value="bar">Bar Chart (柱状图)</option>
                <option value="line">Line Chart (折线图)</option>
                <option value="pie">Pie Chart (饼图)</option>
            </select>
            {error ? (
                <p className="error-message">{error}</p>
            ) : (
                <div className="chart-display">
                    {renderChart()}
                </div>
            )}
        </div>
    );
}

export default ChartPage;